package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"slow-job-seeker/cache"
	"slow-job-seeker/model"
	"strconv"
	"time"
)

func RepoOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var list []model.RepoOrderList
	/*
		SELECT
		  repo_orders.id AS OrderID,
		  repos.repo_code AS RepoCode,
		  repos.repo_name AS RepoName,
		  repo_orders.order_code AS OrderCode,
		  repo_orders.good_num AS GoodNum,
		  repo_orders.order_name AS OrderName
		FROM
		  repo_orders
		  LEFT JOIN repos ON repos.id = repo_orders.rid
	*/
	redis_key := "repo_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select(
				"repo_orders.id AS OrderID",
				"repos.repo_code AS RepoCode",
				"repos.repo_name AS RepoName",
				"repo_orders.order_code AS OrderCode",
				"repo_orders.good_num AS GoodNum",
				"repo_orders.order_name AS OrderName",
			).
			Joins("LEFT JOIN repos ON repos.id = repo_orders.rid").
			Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(&list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return
}

func RepoOrderDetail(c *gin.Context) {
	id := c.Query("id")
	var detail model.RepoOrderList
	/*
		SELECT
		  repo_orders.id AS OrderID,
		  repos.repo_code AS RepoCode,
		  repos.repo_name AS RepoName,
		  repo_orders.order_code AS OrderCode,
		  repo_orders.good_num AS GoodNum,
		  repo_orders.order_name AS OrderName
		FROM
		  repo_orders
		  LEFT JOIN repos ON repos.id = repo_orders.rid
	*/
	redis_key := "repo_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("repo_orders").
			Select(
				"repo_orders.id AS OrderID",
				"repos.repo_code AS RepoCode",
				"repos.repo_name AS RepoName",
				"repo_orders.order_code AS OrderCode",
				"repo_orders.good_num AS GoodNum",
				"repo_orders.order_name AS OrderName",
			).
			Joins("LEFT JOIN repos ON repos.id = repo_orders.rid").
			Where("repo_orders.id = ?", id).Debug().Find(&detail)
		jsonData, _ := json.Marshal(&detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": detail,
	})
	return
}
